// 关卡管理系统
class LevelManager {
    constructor() {
        this.currentLevel = 1;
        this.maxLevel = 20;
        this.levels = this.initializeLevels();
        this.isLevelActive = false;
        this.levelStartTime = 0;
        this.zombieSpawner = new ZombieSpawner();
        this.powerUpSpawner = new PowerUpSpawner();
        this.weaponSpawner = new WeaponSpawner();
        this.setupSpawnPoints();
    }
    
    initializeLevels() {
        return [
            // 第1关 - 教学关
            {
                level: 1,
                name: "教学楼入口",
                description: "僵尸病毒刚刚爆发，你需要清理教学楼入口的少量僵尸",
                zombieCount: 5,
                zombieTypes: ['normal'],
                timeLimit: 120000, // 2分钟
                background: "classroom",
                objectives: ["消灭所有僵尸", "熟悉操作"],
                rewards: { score: 100, weapons: ['pistol'] }
            },
            
            // 第2关 - 走廊清理
            {
                level: 2,
                name: "学校走廊",
                description: "走廊里有更多的僵尸，小心它们的包围",
                zombieCount: 8,
                zombieTypes: ['normal'],
                timeLimit: 150000, // 2.5分钟
                background: "hallway",
                objectives: ["清理走廊", "收集弹药"],
                rewards: { score: 200, weapons: ['rifle'] }
            },
            
            // 第3关 - 图书馆
            {
                level: 3,
                name: "图书馆惊魂",
                description: "图书馆里的僵尸行动缓慢，但数量众多",
                zombieCount: 12,
                zombieTypes: ['normal', 'fast'],
                timeLimit: 180000, // 3分钟
                background: "library",
                objectives: ["保护图书馆", "找到更好的武器"],
                rewards: { score: 300, weapons: ['shotgun'] }
            },
            
            // 第4关 - 实验室
            {
                level: 4,
                name: "化学实验室",
                description: "实验室是病毒的源头，这里的僵尸更加危险",
                zombieCount: 15,
                zombieTypes: ['normal', 'fast', 'spitter'],
                timeLimit: 200000, // 3分20秒
                background: "laboratory",
                objectives: ["清理实验室", "避免化学泄漏"],
                rewards: { score: 500, weapons: ['smg'] }
            },
            
            // 第5关 - 食堂大战
            {
                level: 5,
                name: "学校食堂",
                description: "食堂空间开阔，但僵尸数量激增，准备迎接挑战",
                zombieCount: 20,
                zombieTypes: ['normal', 'fast', 'tank'],
                timeLimit: 240000, // 4分钟
                background: "cafeteria",
                objectives: ["清理食堂", "生存4分钟"],
                rewards: { score: 800, weapons: ['rifle', 'shotgun'] }
            },
            
            // 第6关 - 体育馆
            {
                level: 6,
                name: "体育馆血战",
                description: "宽阔的体育馆成为了僵尸的聚集地，坦克型僵尸开始出现",
                zombieCount: 25,
                zombieTypes: ['normal', 'fast', 'tank', 'spitter'],
                timeLimit: 300000, // 5分钟
                background: "gymnasium",
                objectives: ["占领体育馆", "击败坦克僵尸"],
                rewards: { score: 1200, weapons: ['smg', 'rifle'] }
            },
            
            // 第7关 - 宿舍楼
            {
                level: 7,
                name: "宿舍楼围困",
                description: "宿舍楼的狭窄空间让战斗变得更加困难",
                zombieCount: 30,
                zombieTypes: ['normal', 'fast', 'tank', 'spitter'],
                timeLimit: 320000, // 5分20秒
                background: "dormitory",
                objectives: ["清理宿舍楼", "在狭窄空间中生存"],
                rewards: { score: 1500, weapons: ['shotgun', 'smg'] }
            },
            
            // 第8关 - 天台决战
            {
                level: 8,
                name: "天台最后防线",
                description: "退守到学校天台，四面楚歌，僵尸从各个方向涌来",
                zombieCount: 35,
                zombieTypes: ['fast', 'tank', 'spitter'],
                timeLimit: 360000, // 6分钟
                background: "rooftop",
                objectives: ["守住天台", "等待救援"],
                rewards: { score: 2000, weapons: ['rifle', 'smg', 'shotgun'] }
            },
            
            // 第9关 - 地下室
            {
                level: 9,
                name: "地下室深渊",
                description: "地下室是僵尸的巢穴，这里聚集了最危险的变异体",
                zombieCount: 40,
                zombieTypes: ['tank', 'spitter'],
                timeLimit: 400000, // 6分40秒
                background: "basement",
                objectives: ["深入地下室", "消灭巢穴"],
                rewards: { score: 2500, weapons: ['rifle', 'smg'] }
            },
            
            // 第10关 - 终极BOSS战（大幅降低难度）
            {
                level: 10,
                name: "校长室终极对决",
                description: "病毒源头就在校长室，准备面对史上最强BOSS！这将是你生存技能的终极考验！",
                zombieCount: 3, // 大幅降低：只有3个初始小怪
                zombieTypes: ['fast', 'tank', 'spitter'], // 增加吐痰僵尸
                eliteZombieCount: 1, // 再次减少：只有1个精英僵尸
                eliteZombieTypes: ['fast', 'tank'], // 精英僵尸类型
                timeLimit: 420000, // 保持7分钟时间
                background: "principal_office",
                objectives: ["击败增强版终极BOSS", "生存BOSS的4个阶段", "消灭所有精英小怪", "在7分钟内完成挑战"],
                rewards: { score: 20000, weapons: [] }, // 增加奖励分数
                isBossLevel: true,
                isEnhancedBoss: true,
                // 移除地狱模式标记，第10关正常开始
                bossType: 'ultimate_principal',
                environmentHazards: true, // 环境危险
                continuousSpawn: true, // 持续生成小怪
                phaseBasedSpawn: true, // 新增：基于BOSS阶段的生成机制
                zombiesPerPhase: 4 // 每个BOSS阶段增加3-5个怪物（通过随机实现）
            },
            
            // === 第二阶段：11-15关 - 中级难度阶段 ===
            
            // 第11关 - 新威胁登场（降低难度）
            {
                level: 11,
                name: "实验室深层",
                description: "深入实验室，新的变异体开始出现，爆炸僵尸威胁巨大",
                zombieCount: 18, // 降低：25 → 18
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'exploder'], // 保留原有+新增1个
                timeLimit: 540000, // 增加：7.5分钟 → 9分钟
                background: "deep_laboratory",
                objectives: ["清理深层实验室", "小心爆炸僵尸", "避免连锁爆炸"],
                rewards: { score: 3000, weapons: ['sniper', 'minigun'] }
            },
            
            // 第12关 - 电击威胁（降低难度）
            {
                level: 12,
                name: "发电站危机",
                description: "发电站的辐射产生了电击僵尸，它们的放电攻击极其危险",
                zombieCount: 22, // 降低：30 → 22
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'exploder', 'electric'], // 保留原有+新增1个
                timeLimit: 570000, // 增加：8分钟 → 9.5分钟
                background: "power_station",
                objectives: ["清理发电站", "避免电击伤害", "恢复电力供应"],
                rewards: { score: 3500, weapons: ['laser', 'plasma'] }
            },
            
            // 第13关 - 隐身猎杀（降低难度）
            {
                level: 13,
                name: "废弃医院",
                description: "医院里出现了隐身僵尸，它们会突然现身攻击，保持警惕！",
                zombieCount: 25, // 降低：35 → 25
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'exploder', 'electric', 'stealth'], // 保留原有+新增1个
                timeLimit: 600000, // 增加：8.5分钟 → 10分钟
                background: "abandoned_hospital",
                objectives: ["搜索医院", "追踪隐身僵尸", "收集医疗物资"],
                rewards: { score: 4000, weapons: ['sniper', 'laser'] }
            },
            
            // 第14关 - 巨型威胁（降低难度）
            {
                level: 14,
                name: "工厂废墟",
                description: "工厂的化学泄漏造就了巨型僵尸，它们体型庞大、血量极高",
                zombieCount: 26, // 降低：35 → 26
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'exploder', 'electric', 'stealth', 'giant'], // 保留原有+新增1个
                timeLimit: 630000, // 增加：9分钟 → 10.5分钟
                background: "factory_ruins",
                objectives: ["摧毁巨型僵尸", "清理工厂废墟", "避免化学泄漏"],
                rewards: { score: 4500, weapons: ['minigun', 'plasma'] }
            },
            
            // 第15关 - 分裂噩梦（降低难度）
            {
                level: 15,
                name: "研究中心核心",
                description: "研究中心的核心区域有分裂僵尸，死后会分裂成更多敌人",
                zombieCount: 28, // 降低：40 → 28
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'exploder', 'electric', 'stealth', 'giant', 'splitter'], // 保留原有+新增1个
                timeLimit: 660000, // 增加：9.5分钟 → 11分钟
                background: "research_core",
                objectives: ["突破核心防线", "阻止分裂扩散", "获取核心数据"],
                rewards: { score: 5000, weapons: ['laser', 'plasma'] }
            },
            
            // === 第三阶段：16-19关 - 高级难度阶段 ===
            
            // 第16关 - 治愈者的诅咒（降低难度）
            {
                level: 16,
                name: "感染区边界",
                description: "边界出现了治愈僵尸，它们会恢复其他僵尸的血量，必须优先消灭",
                zombieCount: 32, // 降低：45 → 32
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'exploder', 'electric', 'stealth', 'giant', 'splitter', 'healer'], // 保留原有+新增1个
                timeLimit: 720000, // 增加：10分钟 → 12分钟
                background: "infection_border",
                objectives: ["突破感染边界", "优先击杀治愈者", "防止僵尸回血"],
                rewards: { score: 6000, weapons: ['sniper', 'minigun', 'laser'] }
            },
            
            // 第17关 - 狂暴军团（降低难度）
            {
                level: 17,
                name: "军事基地沦陷",
                description: "军事基地被狂暴僵尸占领，它们血量越低速度越快，极其危险",
                zombieCount: 35, // 降低：50 → 35
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'exploder', 'electric', 'stealth', 'giant', 'splitter', 'healer', 'berserker'], // 保留原有+新增1个
                timeLimit: 750000, // 增加：10.5分钟 → 12.5分钟
                background: "military_base",
                objectives: ["夺回军事基地", "击败狂暴军团", "获取军用装备"],
                rewards: { score: 7000, weapons: ['minigun', 'plasma', 'laser'] }
            },
            
            // 第18关 - 混沌战场（降低难度）
            {
                level: 18,
                name: "混沌战场",
                description: "所有类型的变异僵尸聚集在此，这是最后的战场准备",
                zombieCount: 38, // 降低：55 → 38
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'exploder', 'electric', 'stealth', 'giant', 'splitter', 'healer', 'berserker'], // 所有类型
                timeLimit: 780000, // 增加：11分钟 → 13分钟
                background: "chaos_battlefield",
                objectives: ["征服混沌战场", "击败所有变异体", "为最终战做准备"],
                rewards: { score: 8000, weapons: ['plasma', 'laser'] },
                environmentHazards: true, // 环境危险
                continuousSpawn: true // 持续生成
            },
            
            // 第19关 - 病毒源头前哨（降低难度）
            {
                level: 19,
                name: "源头前哨",
                description: "接近病毒的真正源头，强大的僵尸守卫着通往最终战的道路",
                zombieCount: 40, // 降低：60 → 40
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'exploder', 'electric', 'stealth', 'giant', 'splitter', 'healer', 'berserker'], // 所有类型
                eliteZombieCount: 5, // 降低：8 → 5
                eliteZombieTypes: ['giant', 'berserker'],
                timeLimit: 810000, // 增加：11.5分钟 → 13.5分钟
                background: "virus_origin_outpost",
                objectives: ["突破源头前哨", "击败所有守卫", "准备最终决战"],
                rewards: { score: 9000, weapons: [] },
                environmentHazards: true,
                continuousSpawn: true,
                phaseBasedSpawn: false,
                isPreBossLevel: true // 准BOSS关卡
            },
            
            // === 第20关 - 终极BOSS战（降低难度）===
            {
                level: 20,
                name: "病毒原始体歼灭战",
                description: "这是最终的决战！病毒的原始体拥有史无前例的力量，6个战斗阶段，环境操控，分身术，流星雨...你准备好了吗？",
                zombieCount: 6, // 降低：10 → 6
                zombieTypes: ['normal', 'fast', 'tank', 'spitter', 'giant', 'berserker', 'healer'], // 包含原有+最强僵尸类型
                eliteZombieCount: 3, // 降低：5 → 3
                eliteZombieTypes: ['giant', 'berserker'],
                timeLimit: 1080000, // 增加：15分钟 → 18分钟
                background: "virus_origin_core",
                objectives: [
                    "击败病毒原始体", 
                    "生存6个BOSS阶段", 
                    "应对环境操控", 
                    "击败BOSS分身",
                    "躲避流星雨攻击",
                    "拯救世界"
                ],
                rewards: { score: 50000, weapons: [] }, // 史诗级奖励
                isBossLevel: true,
                isUltimateBoss: true, // 终极BOSS标记
                bossType: 'virus_origin', // 终极BOSS类型
                environmentHazards: true,
                continuousSpawn: true,
                phaseBasedSpawn: true,
                zombiesPerPhase: 4, // 降低：每阶段小怪 6 → 4
                hasMultipleAttackModes: true, // 多种攻击模式
                hasBossClones: true, // BOSS分身
                hasEnvironmentControl: true, // 环境操控
                finalBattle: true // 最终战标记
            }
        ];
    }
    
    setupSpawnPoints() {
        const canvas = document.getElementById('gameCanvas');
        if (!canvas) {
            console.warn('setupSpawnPoints: canvas not found, using default spawn points');
            // 使用默认尺寸 1000x750
            const defaultWidth = 1000;
            const defaultHeight = 750;
            const commonSpawnPoints = [
                { x: 50, y: 50 },
                { x: defaultWidth - 50, y: 50 },
                { x: 50, y: defaultHeight - 50 },
                { x: defaultWidth - 50, y: defaultHeight - 50 },
                { x: defaultWidth / 2, y: 50 },
                { x: defaultWidth / 2, y: defaultHeight - 50 }
            ];
            
            commonSpawnPoints.forEach(point => {
                this.zombieSpawner.addSpawnPoint(point.x, point.y);
            });
            return;
        }
        
        // 为每个关卡设置不同的生成点
        const commonSpawnPoints = [
            { x: 50, y: 50 },
            { x: canvas.width - 50, y: 50 },
            { x: 50, y: canvas.height - 50 },
            { x: canvas.width - 50, y: canvas.height - 50 },
            { x: canvas.width / 2, y: 50 },
            { x: canvas.width / 2, y: canvas.height - 50 }
        ];
        
        commonSpawnPoints.forEach(point => {
            this.zombieSpawner.addSpawnPoint(point.x, point.y);
            this.weaponSpawner.addSpawnPoint(point.x, point.y);
        });
    }
    
    startLevel(levelNumber) {
        window.debugLog && window.debugLog(`LevelManager.startLevel(${levelNumber}) 开始`);
        
        try {
            if (levelNumber < 1 || levelNumber > this.maxLevel) {
                throw new Error(`无效的关卡号: ${levelNumber}`);
            }
            
            this.currentLevel = levelNumber;
            const levelData = this.levels[levelNumber - 1];
            if (!levelData) {
                throw new Error(`找不到关卡数据: ${levelNumber}`);
            }
            
            this.isLevelActive = true;
            this.levelStartTime = Date.now();
            window.debugLog && window.debugLog(`关卡${levelNumber}基本设置完成`);
            
            console.log('开始关卡', levelNumber, '数据:', levelData);
            
            // 确保游戏状态为playing
            if (window.gameEngine) {
                window.gameEngine.gameState = 'playing';
                console.log('游戏状态设置为:', window.gameEngine.gameState);
                window.debugLog && window.debugLog('游戏状态设置为playing');
            } else {
                throw new Error('gameEngine 不可用于设置游戏状态');
            }
            
            // 所有关卡都直接开始游戏
            window.debugLog && window.debugLog('调用actuallyStartLevel...');
            this.actuallyStartLevel(levelData);
            window.debugLog && window.debugLog('actuallyStartLevel完成');
            
            window.debugLog && window.debugLog(`✓ 关卡${levelNumber}启动成功`);
            return true;
        } catch (error) {
            console.error('startLevel失败:', error);
            window.debugLog && window.debugLog(`✗ 关卡${levelNumber}启动失败: ` + error.message);
            throw error;
        }
    }
    
    // 移除了showLevelIntro方法 - 第10关直接开始，无弹窗
    
    actuallyStartLevel(levelData) {
        window.debugLog && window.debugLog('actuallyStartLevel 开始');
        console.log('actuallyStartLevel called with:', levelData);
        
        try {
            // 确保清理之前的状态
            if (window.gameEngine) {
                window.gameEngine.zombies = [];
                window.gameEngine.bullets = [];
                window.gameEngine.particles = [];
                window.gameEngine.powerUps = [];
                window.gameEngine.bossProjectiles = [];
                window.gameEngine.floatingTexts = [];
                window.gameEngine.meleeWeapons = []; // 清理近战武器
                window.gameEngine.boss = null;
            }
            
            // 重置武器生成器（每关只生成一次）
            if (this.weaponSpawner) {
                this.weaponSpawner.resetForNewLevel();
            }
            // 确保玩家存在
            window.debugLog && window.debugLog('检查玩家...');
            if (!window.player) {
                const canvas = document.getElementById('gameCanvas');
                if (!canvas) {
                    throw new Error('找不到游戏画布');
                }
                window.player = new Player(canvas.width / 2, canvas.height / 2);
                console.log('创建玩家:', window.player);
                window.debugLog && window.debugLog('玩家创建完成');
                
                // 新创建的玩家立即应用技能效果
                window.debugLog && window.debugLog('对新创建的玩家应用技能效果...');
                this.applySkillEffectsToPlayer();
            } else {
                // 玩家已存在，但仍需要重新应用技能效果（关卡切换时）
                window.debugLog && window.debugLog('玩家已存在，重新应用技能效果...');
                this.applySkillEffectsToPlayer();
            }
            
            // 确保玩家血量为满血（特别是在重新开始游戏时）
            if (window.player) {
                window.player.health = window.player.maxHealth;
                window.player.updateHealthUI();
                window.debugLog && window.debugLog('玩家血量已重置为满血');
            }
            
            // 更新UI
            window.debugLog && window.debugLog('更新关卡UI...');
            this.updateLevelUI();
            
            // 额外清理（已在上面做了）
            window.debugLog && window.debugLog('游戏对象清理完成');
            
            // 第10关和第20关生成Boss，其他关卡生成僵尸
            if (this.currentLevel === 10 || this.currentLevel === 20) {
                window.debugLog && window.debugLog(`🔥 第${this.currentLevel}关BOSS模式，生成Boss和精英僵尸...`);
                this.spawnBoss();
                
                // 第10关特殊：生成精英僵尸群
                this.spawnEliteZombies(levelData);
                
                // 启动持续生成系统
                if (levelData.continuousSpawn) {
                    this.startContinuousSpawn(levelData);
                }
            } else {
                window.debugLog && window.debugLog(`第${this.currentLevel}关，生成僵尸...`);
                // 检查zombieSpawner
                if (!this.zombieSpawner) {
                    throw new Error('zombieSpawner 不可用');
                }
                
                // 生成僵尸
                window.debugLog && window.debugLog('调用zombieSpawner.spawnWave...');
                const zombies = this.zombieSpawner.spawnWave(this.currentLevel);
                console.log('生成僵尸:', zombies.length, '只');
                window.debugLog && window.debugLog(`生成了${zombies.length}只僵尸`);
                
                if (window.gameEngine) {
                    window.gameEngine.zombies = zombies;
                    console.log('僵尸已添加到游戏引擎');
                    window.debugLog && window.debugLog('僵尸已添加到游戏引擎');
                } else {
                    throw new Error('gameEngine 不可用于添加僵尸');
                }
            }
            
            // 生成武器奖励
            try {
                window.debugLog && window.debugLog('生成武器奖励...');
                this.spawnLevelWeapons(levelData);
                window.debugLog && window.debugLog('武器生成完成');
            } catch (weaponError) {
                console.error('武器生成失败:', weaponError);
                window.debugLog && window.debugLog('武器生成失败: ' + weaponError.message);
            }
            
            // 生成初始道具
            try {
                window.debugLog && window.debugLog('生成初始道具...');
                this.spawnInitialPowerUps();
                window.debugLog && window.debugLog('道具生成完成');
            } catch (powerUpError) {
                console.error('道具生成失败:', powerUpError);
                window.debugLog && window.debugLog('道具生成失败: ' + powerUpError.message);
            }
            
            console.log(`第${this.currentLevel}关正式开始: ${levelData.name}`);
            window.debugLog && window.debugLog(`✓ 第${this.currentLevel}关启动完成`);
        } catch (error) {
            console.error('actuallyStartLevel 失败:', error);
            window.debugLog && window.debugLog('✗ actuallyStartLevel 失败: ' + error.message);
            throw error;
        }
    }
    
    spawnBoss() {
        try {
            const canvas = document.getElementById('gameCanvas');
            if (!canvas) {
                throw new Error('找不到游戏画布');
            }
            
            const levelData = this.levels[this.currentLevel - 1];
            let boss;
            
            // 第20关：终极BOSS
            if (this.currentLevel === 20 && levelData.isUltimateBoss && typeof UltimateBoss !== 'undefined') {
                console.log('👹 创建终极BOSS - 病毒原始体！');
                const bossType = levelData.bossType || 'virus_origin';
                boss = new UltimateBoss(canvas.width / 2, 200, bossType);
                
                console.log('👹👹👹 终极BOSS降临！这是史无前例的最终决战！👹👹👹');
                
            // 第10关：增强版BOSS
            } else if (this.currentLevel === 10 && levelData.isEnhancedBoss && typeof EnhancedBoss !== 'undefined') {
                console.log('💀 创建增强版终极BOSS！');
                const bossType = levelData.bossType || 'ultimate_principal';
                boss = new EnhancedBoss(canvas.width / 2, 200, bossType);
                
                console.log('💀💀💀 史上最强BOSS已降临！准备迎接终极挑战！💀💀💀');
                
            // 标准BOSS
            } else if (typeof Boss !== 'undefined') {
                console.log('创建标准BOSS');
                boss = new Boss(canvas.width / 2, 100, 'principal');
            } else {
                throw new Error('Boss类未定义');
            }
            
            if (window.gameEngine && boss) {
                window.gameEngine.boss = boss;
                console.log(`第${this.currentLevel}关Boss已生成!`);
                window.debugLog && window.debugLog(`第${this.currentLevel}关Boss创建成功`);
            } else {
                throw new Error('gameEngine不可用或boss创建失败');
            }
        } catch (error) {
            console.error('Boss生成失败:', error);
            window.debugLog && window.debugLog('Boss生成失败: ' + error.message);
            throw error;
        }
    }
    
    // 显示BOSS警告
    // showBossWarning() 方法已移除 - 第10关直接开始
    removedShowBossWarning() {
        const warningDiv = document.createElement('div');
        warningDiv.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: linear-gradient(135deg, rgba(139, 0, 0, 0.95), rgba(220, 20, 60, 0.95));
            color: #FFD700;
            padding: 30px 40px;
            border-radius: 20px;
            border: 3px solid #FFD700;
            box-shadow: 
                0 20px 50px rgba(139, 0, 0, 0.6),
                inset 0 2px 0 rgba(255, 255, 255, 0.3);
            z-index: 20000;
            text-align: center;
            font-family: 'Courier New', monospace;
            font-size: 18px;
            font-weight: bold;
            animation: bossWarningPulse 2s ease-in-out infinite;
        `;
        
        warningDiv.innerHTML = `
            <div style="font-size: 32px; margin-bottom: 15px;">💀 ⚠️ BOSS战开始 ⚠️ 💀</div>
            <div style="font-size: 24px; color: #FF4500; margin-bottom: 10px;">史上最强BOSS降临！</div>
            <div style="font-size: 16px; margin-bottom: 15px;">
                • 1500血量，4个战斗阶段<br>
                • 终极连击技能组合<br>
                • 绝望突击疯狂模式<br>
                • 弹幕地狱与流星暴雨<br>
                • 会召唤小怪和分身<br>
                • 超级冲击波多层攻击<br>
                • 史无前例的挑战难度
            </div>
            <div style="font-size: 20px; color: #FFD700;">你真的准备好面对终极噩梦了吗？</div>
            <div style="font-size: 14px; color: #FF6B6B; margin-top: 10px;">建议：确保满血、充足弹药、最强武器</div>
        `;
        
        document.body.appendChild(warningDiv);
        
        // 添加警告动画
        if (!document.getElementById('bossWarningStyles')) {
            const styles = document.createElement('style');
            styles.id = 'bossWarningStyles';
            styles.textContent = `
                @keyframes bossWarningPulse {
                    0%, 100% { 
                        transform: translate(-50%, -50%) scale(1);
                        box-shadow: 
                            0 20px 50px rgba(139, 0, 0, 0.6),
                            inset 0 2px 0 rgba(255, 255, 255, 0.3);
                    }
                    50% { 
                        transform: translate(-50%, -50%) scale(1.05);
                        box-shadow: 
                            0 25px 60px rgba(139, 0, 0, 0.8),
                            inset 0 2px 0 rgba(255, 255, 255, 0.4);
                    }
                }
            `;
            document.head.appendChild(styles);
        }
        
        // 5秒后移除警告
        setTimeout(() => {
            if (warningDiv.parentNode) {
                warningDiv.style.animation = 'fadeOut 1s ease-in';
                setTimeout(() => {
                    if (warningDiv.parentNode) {
                        document.body.removeChild(warningDiv);
                    }
                }, 1000);
            }
        }, 5000);
    }
    
    spawnInitialPowerUps() {
        if (this.currentLevel === 1) return; // 第一关不生成道具
        
        const canvas = document.getElementById('gameCanvas');
        const numPowerUps = Math.min(2, Math.floor(this.currentLevel / 3) + 1);
        
        for (let i = 0; i < numPowerUps; i++) {
            const x = Math.random() * (canvas.width - 200) + 100;
            const y = Math.random() * (canvas.height - 200) + 100;
            
            const powerUpTypes = ['health', 'ammo'];
            if (this.currentLevel >= 3) powerUpTypes.push('speed');
            if (this.currentLevel >= 5) powerUpTypes.push('damage', 'shield');
            if (this.currentLevel >= 7) powerUpTypes.push('rapid_fire', 'explosive');
            
            const randomType = powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)];
            this.powerUpSpawner.spawnSpecificPowerUp(randomType, x, y);
        }
    }
    
    spawnLevelWeapons(levelData) {
        // 首先始终生成近战武器（不受rewards.weapons影响）
        console.log(`开始为第${this.currentLevel}关生成武器...`);
        this.spawnInitialMeleeWeapons();
        
        // 然后生成关卡奖励武器（如果有的话）
        if (levelData.rewards.weapons && levelData.rewards.weapons.length > 0) {
            const canvas = document.getElementById('gameCanvas');
            const weaponPositions = [
                { x: canvas.width * 0.2, y: canvas.height * 0.3 },
                { x: canvas.width * 0.8, y: canvas.height * 0.7 },
                { x: canvas.width * 0.5, y: canvas.height * 0.5 }
            ];
            
            levelData.rewards.weapons.forEach((weaponType, index) => {
                if (index < weaponPositions.length) {
                    const weapon = new Weapon(weaponType, 20, 100, 0, 0);
                    const pos = weaponPositions[index];
                    weapon.drop(pos.x, pos.y);
                    
                    if (window.gameEngine) {
                        window.gameEngine.weapons.push(weapon);
                    }
                }
            });
            
            console.log(`生成了${levelData.rewards.weapons.length}个关卡奖励武器`);
        } else {
            console.log('本关卡没有关卡奖励武器，只生成基础武器');
        }
    }
    
    spawnInitialMeleeWeapons() {
        console.log(`🗡️ 开始生成第${this.currentLevel}关的近战武器...`);
        const canvas = document.getElementById('gameCanvas');
        const meleePositions = [
            { x: canvas.width * 0.1, y: canvas.height * 0.8 },
            { x: canvas.width * 0.9, y: canvas.height * 0.2 },
            { x: canvas.width * 0.5, y: canvas.height * 0.1 }, // 第10关额外位置
            { x: canvas.width * 0.2, y: canvas.height * 0.3 },
            { x: canvas.width * 0.8, y: canvas.height * 0.7 }
        ];
        
        // 根据关卡生成近战武器
        let meleeTypes = [];
        let numMeleeWeapons = 1;
        
        if (this.currentLevel <= 2) {
            meleeTypes = ['knife'];
            numMeleeWeapons = 1;
        } else if (this.currentLevel <= 4) {
            meleeTypes = ['knife', 'bat'];
            numMeleeWeapons = 1;
        } else if (this.currentLevel <= 7) {
            meleeTypes = ['bat', 'sword'];
            numMeleeWeapons = 2;
        } else if (this.currentLevel <= 9) {
            meleeTypes = ['sword', 'axe'];
            numMeleeWeapons = 2;
        } else {
            // 第10关 - 生成所有高级近战武器
            console.log('🌟 检测到第10关，准备生成增强版近战武器！');
            meleeTypes = ['sword', 'axe'];
            numMeleeWeapons = 3; // 第10关生成更多武器
        }
        
        console.log(`准备生成${numMeleeWeapons}个近战武器，类型: [${meleeTypes.join(', ')}]`);
        
        for (let i = 0; i < numMeleeWeapons && i < meleePositions.length; i++) {
            const randomType = meleeTypes[Math.floor(Math.random() * meleeTypes.length)];
            const meleeWeapon = new MeleeWeapon(randomType);
            
            console.log(`正在生成第${i+1}个近战武器: ${randomType}`);
            
            // 第10关近战武器buff加成
            if (this.currentLevel === 10) {
                console.log(`⚡ 应用第10关buff加成到${randomType}...`);
                const originalDamage = meleeWeapon.stats.damage;
                const originalRange = meleeWeapon.stats.range;
                const originalSpeed = meleeWeapon.stats.attackSpeed;
                
                meleeWeapon.stats.damage = Math.floor(meleeWeapon.stats.damage * 1.8); // 伤害增强80%
                meleeWeapon.stats.range = Math.floor(meleeWeapon.stats.range * 1.3); // 范围增强30%
                meleeWeapon.stats.attackSpeed = Math.floor(meleeWeapon.stats.attackSpeed * 0.7); // 攻击速度提升30%
                meleeWeapon.damage = meleeWeapon.stats.damage; // 更新实际伤害值
                meleeWeapon.range = meleeWeapon.stats.range; // 更新实际范围值
                meleeWeapon.attackSpeed = meleeWeapon.stats.attackSpeed; // 更新实际攻击速度
                
                console.log(`✨ ${randomType} buff应用完成! 伤害: ${originalDamage}→${meleeWeapon.stats.damage}, 范围: ${originalRange}→${meleeWeapon.stats.range}, 攻速: ${originalSpeed}→${meleeWeapon.stats.attackSpeed}`);
            }
            
            meleeWeapon.drop(meleePositions[i].x, meleePositions[i].y);
            console.log(`近战武器已放置在位置: (${meleePositions[i].x}, ${meleePositions[i].y})`);
            
            if (window.gameEngine) {
                if (!window.gameEngine.meleeWeapons) {
                    window.gameEngine.meleeWeapons = [];
                }
                window.gameEngine.meleeWeapons.push(meleeWeapon);
                console.log(`近战武器已添加到游戏引擎，当前总数: ${window.gameEngine.meleeWeapons.length}`);
            }
        }
        
        console.log(`✅ 第${this.currentLevel}关生成了${numMeleeWeapons}个近战武器`);
        
        // 第10关额外生成高级远程武器
        if (this.currentLevel === 10) {
            console.log('🔫 第10关检测到，开始生成高级远程武器...');
            this.spawnBossLevelRangedWeapons();
        }
    }
    
    // 第10关生成高级远程武器
    spawnBossLevelRangedWeapons() {
        console.log('🔫 spawnBossLevelRangedWeapons() 开始执行...');
        const canvas = document.getElementById('gameCanvas');
        const rangedPositions = [
            { x: canvas.width * 0.3, y: canvas.height * 0.6 },
            { x: canvas.width * 0.7, y: canvas.height * 0.4 },
            { x: canvas.width * 0.15, y: canvas.height * 0.5 }
        ];
        
        // 第10关的高级武器类型
        const eliteWeaponTypes = ['sniper', 'minigun', 'laser', 'plasma'];
        console.log(`准备生成3个高级远程武器，类型池: [${eliteWeaponTypes.join(', ')}]`);
        
        for (let i = 0; i < 3 && i < rangedPositions.length; i++) {
            const weaponType = eliteWeaponTypes[i % eliteWeaponTypes.length];
            console.log(`正在生成第${i+1}个远程武器: ${weaponType}`);
            
            // 创建增强版武器（高弹药和伤害buff）
            const weapon = new Weapon(weaponType, 
                Math.floor(Math.random() * 50) + 50, // 高弹药 50-100
                Math.floor(Math.random() * 200) + 200, // 高总弹药 200-400
                0, 0
            );
            
            // 记录原始属性
            const originalDamage = weapon.weaponStats.damage;
            const originalFireRate = weapon.weaponStats.fireRate;
            const originalBulletSpeed = weapon.weaponStats.bulletSpeed;
            
            // 为第10关武器添加特殊buff
            weapon.weaponStats.damage = Math.floor(weapon.weaponStats.damage * 1.5); // 伤害增强50%
            weapon.weaponStats.fireRate = Math.floor(weapon.weaponStats.fireRate * 0.8); // 射速提升25%
            weapon.weaponStats.bulletSpeed = Math.floor(weapon.weaponStats.bulletSpeed * 1.2); // 子弹速度增强20%
            
            console.log(`⚡ ${weaponType} buff应用完成! 伤害: ${originalDamage}→${weapon.weaponStats.damage}, 射速: ${originalFireRate}→${weapon.weaponStats.fireRate}, 弹速: ${originalBulletSpeed}→${weapon.weaponStats.bulletSpeed}`);
            
            weapon.drop(rangedPositions[i].x, rangedPositions[i].y);
            console.log(`远程武器已放置在位置: (${rangedPositions[i].x}, ${rangedPositions[i].y})`);
            
            if (window.gameEngine) {
                if (!window.gameEngine.weapons) {
                    window.gameEngine.weapons = [];
                }
                window.gameEngine.weapons.push(weapon);
                console.log(`远程武器已添加到游戏引擎，当前总数: ${window.gameEngine.weapons.length}`);
            } else {
                console.error('❌ window.gameEngine 不存在，无法添加远程武器！');
            }
        }
        
        console.log('✅ 第10关生成了3个增强版高级远程武器');
    }
    
    // 第10关：生成精英僵尸群
    spawnEliteZombies(levelData) {
        console.log('🔥💀 开始生成精英僵尸群...');
        
        if (!levelData.eliteZombieCount || !levelData.eliteZombieTypes) {
            console.log('❌ 没有精英僵尸配置');
            return;
        }
        
        const canvas = document.getElementById('gameCanvas');
        const elitePositions = [
            { x: canvas.width * 0.1, y: canvas.height * 0.1 },
            { x: canvas.width * 0.9, y: canvas.height * 0.1 },
            { x: canvas.width * 0.1, y: canvas.height * 0.9 },
            { x: canvas.width * 0.9, y: canvas.height * 0.9 },
            { x: canvas.width * 0.3, y: canvas.height * 0.2 },
            { x: canvas.width * 0.7, y: canvas.height * 0.2 },
            { x: canvas.width * 0.3, y: canvas.height * 0.8 },
            { x: canvas.width * 0.7, y: canvas.height * 0.8 }
        ];
        
        const eliteZombies = [];
        
        for (let i = 0; i < levelData.eliteZombieCount && i < elitePositions.length; i++) {
            const randomType = levelData.eliteZombieTypes[Math.floor(Math.random() * levelData.eliteZombieTypes.length)];
            const pos = elitePositions[i];
            
            // 创建精英僵尸（5级，最高级别）
            const eliteZombie = new Zombie(pos.x, pos.y, randomType, 5);
            
            // 精英僵尸特殊增强
            eliteZombie.health = Math.floor(eliteZombie.health * 2.0); // 血量翻倍
            eliteZombie.maxHealth = eliteZombie.health;
            eliteZombie.damage = Math.floor(eliteZombie.damage * 1.5); // 伤害增强50%
            eliteZombie.speed = Math.floor(eliteZombie.speed * 1.3); // 速度增强30%
            eliteZombie.isElite = true; // 标记为精英
            eliteZombie.glowIntensity = 1.0; // 强烈发光效果
            
            eliteZombies.push(eliteZombie);
            console.log(`生成精英${randomType}僵尸，血量: ${eliteZombie.health}, 伤害: ${eliteZombie.damage}`);
        }
        
        // 生成普通小怪
        const normalZombies = [];
        for (let i = 0; i < levelData.zombieCount; i++) {
            const randomType = levelData.zombieTypes[Math.floor(Math.random() * levelData.zombieTypes.length)];
            
            // 随机位置生成
            const x = Math.random() * (canvas.width - 100) + 50;
            const y = Math.random() * (canvas.height - 100) + 50;
            
            // 创建3-4级普通僵尸（比精英弱但比常规强）
            const normalZombie = new Zombie(x, y, randomType, Math.floor(Math.random() * 2) + 3);
            normalZombie.health = Math.floor(normalZombie.health * 1.3); // 血量增强30%
            normalZombie.maxHealth = normalZombie.health;
            normalZombie.damage = Math.floor(normalZombie.damage * 1.2); // 伤害增强20%
            
            normalZombies.push(normalZombie);
        }
        
        // 添加到游戏引擎
        if (window.gameEngine) {
            window.gameEngine.zombies = [...eliteZombies, ...normalZombies];
            console.log(`🔥💀 地狱模式僵尸生成完成！精英: ${eliteZombies.length}, 普通: ${normalZombies.length}, 总计: ${window.gameEngine.zombies.length}`);
        }
    }
    
    // 第10关：启动持续生成系统（调整后难度）
    startContinuousSpawn(levelData) {
        console.log('🔄 启动持续生成系统（调整难度）...');
        
        this.continuousSpawnActive = true;
        this.lastSpawnTime = Date.now();
        this.spawnInterval = 60000; // 调整：每60秒生成一波（进一步降低频率）
        this.maxZombiesOnField = 20; // 调整：进一步降低场上最大僵尸数
        this.currentPhase = 1; // 初始BOSS阶段
        
        // 启动持续生成循环
        this.continuousSpawnTimer = setInterval(() => {
            if (!this.isLevelActive || !this.continuousSpawnActive) {
                clearInterval(this.continuousSpawnTimer);
                return;
            }
            
            // 检查当前BOSS阶段
            this.updateCurrentPhase();
            
            if (window.gameEngine && window.gameEngine.zombies.length < this.maxZombiesOnField) {
                this.spawnReinforcementWave(levelData);
            }
        }, this.spawnInterval);
        
        console.log(`🔄 持续生成系统已启动，每${this.spawnInterval/1000}秒检查一次`);
    }
    
    // 更新当前BOSS阶段
    updateCurrentPhase() {
        if (window.gameEngine && window.gameEngine.bosses && window.gameEngine.bosses.length > 0) {
            const boss = window.gameEngine.bosses[0];
            if (boss && boss.phase) {
                const newPhase = boss.phase;
                if (newPhase !== this.currentPhase) {
                    console.log(`🔄 BOSS阶段变化: ${this.currentPhase} → ${newPhase}`);
                    this.currentPhase = newPhase;
                    
                    // 当BOSS进入新阶段时，立即生成一波增援
                    if (this.currentPhase > 1) {
                        console.log(`💀 BOSS进入阶段${this.currentPhase}，触发即时增援！`);
                        const levelData = this.levels[this.currentLevel - 1];
                        this.spawnReinforcementWave(levelData);
                    }
                }
            }
        }
    }
    
    // 生成增援波次（基于BOSS阶段调整）
    spawnReinforcementWave(levelData) {
        console.log(`🔄💀 生成增援波次（BOSS阶段: ${this.currentPhase}）...`);
        
        const canvas = document.getElementById('gameCanvas');
        const reinforcements = [];
        
        // 根据BOSS阶段调整生成数量：每阶段只增加1-2个怪物
        const baseWaveSize = 0; // 基础生成数量
        const phaseBonus = (this.currentPhase - 1) * (Math.floor(Math.random() * 2) + 1); // 1-2个随机增加
        const waveSize = Math.max(1, baseWaveSize + phaseBonus); // 至少生成1个
        
        console.log(`📈 BOSS阶段${this.currentPhase}，基础${baseWaveSize} + 阶段奖励${phaseBonus} = 总计${waveSize}只增援`);
        
        for (let i = 0; i < waveSize; i++) {
            const randomType = levelData.zombieTypes[Math.floor(Math.random() * levelData.zombieTypes.length)];
            
            // 从边缘生成
            let x, y;
            const edge = Math.floor(Math.random() * 4);
            switch (edge) {
                case 0: // 上边
                    x = Math.random() * canvas.width;
                    y = 0;
                    break;
                case 1: // 右边
                    x = canvas.width;
                    y = Math.random() * canvas.height;
                    break;
                case 2: // 下边
                    x = Math.random() * canvas.width;
                    y = canvas.height;
                    break;
                case 3: // 左边
                    x = 0;
                    y = Math.random() * canvas.height;
                    break;
            }
            
            // 创建增援僵尸（根据BOSS阶段调整等级）
            const zombieLevel = this.getZombieLevelForPhase(this.currentPhase);
            const reinforcement = new Zombie(x, y, randomType, zombieLevel);
            
            // 根据阶段调整僵尸强度
            const phaseMultiplier = 1 + (this.currentPhase - 1) * 0.15; // 每阶段增强15%
            reinforcement.health = Math.floor(reinforcement.health * phaseMultiplier);
            reinforcement.maxHealth = reinforcement.health;
            reinforcement.damage = Math.floor(reinforcement.damage * phaseMultiplier);
            
            reinforcements.push(reinforcement);
        }
        
        // 添加到游戏中
        if (window.gameEngine) {
            window.gameEngine.zombies.push(...reinforcements);
            console.log(`🔄💀 增援波次到达！新增${reinforcements.length}只僵尸，场上总数: ${window.gameEngine.zombies.length}`);
        }
    }
    
    // 应用技能效果到玩家（在每个关卡开始时调用）
    applySkillEffectsToPlayer() {
        try {
            window.debugLog && window.debugLog('🎯 在关卡开始时应用技能树效果...');
            
            // 确保技能树系统存在并应用效果
            if (window.newSkillTree && typeof window.newSkillTree.applySkillEffects === 'function') {
                window.newSkillTree.applySkillEffects();
                
                // 启动技能效果循环（用于生命恢复等持续效果）
                if (typeof window.newSkillTree.startSkillEffectLoop === 'function') {
                    window.newSkillTree.startSkillEffectLoop();
                }
                
                window.debugLog && window.debugLog('✅ 新技能树效果应用成功');
            } else if (window.newSkillTreeSystem && typeof window.newSkillTreeSystem.applySkillEffects === 'function') {
                window.newSkillTreeSystem.applySkillEffects();
                
                // 启动技能效果循环
                if (typeof window.newSkillTreeSystem.startSkillEffectLoop === 'function') {
                    window.newSkillTreeSystem.startSkillEffectLoop();
                }
                
                window.debugLog && window.debugLog('✅ 技能树系统效果应用成功');
            } else {
                window.debugLog && window.debugLog('⚠️ 技能树系统不可用');
            }
            
            // 确保永久升级效果也被应用
            if (window.roguelikeSystem && typeof window.roguelikeSystem.applyPermanentUpgrades === 'function') {
                window.roguelikeSystem.applyPermanentUpgrades();
                window.debugLog && window.debugLog('✅ 永久升级效果应用成功');
            }
            
            console.log(`🎮 关卡${this.currentLevel}开始时技能效果应用完成`);
            
        } catch (error) {
            console.error('❌ 在关卡开始时应用技能效果失败:', error);
            window.debugLog && window.debugLog('技能效果应用失败: ' + error.message);
        }
    }
    
    // 根据BOSS阶段获取僵尸等级
    getZombieLevelForPhase(phase) {
        switch (phase) {
            case 1:
                return 2; // 阶段1：2级僵尸
            case 2:
                return 3; // 阶段2：3级僵尸
            case 3:
                return 4; // 阶段3：4级僵尸
            case 4:
                return 5; // 阶段4：5级僵尸（最高等级）
            default:
                return 2;
        }
    }
    
    completeLevel() {
        if (!this.isLevelActive) return;
        
        // 停止持续生成
        if (this.continuousSpawnTimer) {
            clearInterval(this.continuousSpawnTimer);
            this.continuousSpawnActive = false;
            console.log('🔄 持续生成系统已停止');
        }
        
        const levelData = this.levels[this.currentLevel - 1];
        const completionTime = Date.now() - this.levelStartTime;
        const timeBonus = Math.max(0, levelData.timeLimit - completionTime) / 1000;
        
        // 计算分数
        const baseScore = levelData.rewards.score;
        const timeBonusScore = Math.floor(timeBonus * 10);
        const totalScore = baseScore + timeBonusScore;
        
        this.isLevelActive = false;
        
        // 保存进度
        this.saveProgress();
        
        // 保存最佳分数和关卡完成状态
        if (window.saveSystem) {
            window.saveSystem.saveLevelBestScore(this.currentLevel, totalScore);
            window.saveSystem.saveCompletedLevel(this.currentLevel);
        }
        
        // 标记关卡完成（使用存储管理器）
        if (window.storageManager) {
            window.storageManager.saveProgress({
                level: this.currentLevel,
                completed: true,
                score: totalScore
            });
        }
        
        // 显示完成信息
        this.showLevelComplete(totalScore, timeBonusScore);
        
        // 检查成就
        if (window.achievementSystem) {
            window.achievementSystem.checkAchievements();
        }
        
        // 显示道具选择界面（肉鸽系统）
        if (window.roguelikeSystem && this.currentLevel < this.maxLevel) {
            // 延迟显示道具选择，让玩家先看到关卡完成信息
            setTimeout(() => {
                try {
                    if (window.roguelikeSystem && typeof window.roguelikeSystem.showUpgradeSelection === 'function') {
                        window.roguelikeSystem.showUpgradeSelection();
                    }
                } catch (error) {
                    console.error('显示升级选择失败:', error);
                }
            }, 1500);
        }
        
        return {
            baseScore: baseScore,
            timeBonus: timeBonusScore,
            totalScore: totalScore,
            nextLevel: this.currentLevel + 1
        };
    }
    
    showLevelComplete(totalScore, timeBonus) {
        const menu = document.getElementById('levelCompleteMenu');
        const scoreElement = document.getElementById('levelScore');
        
        if (menu && scoreElement) {
            scoreElement.innerHTML = `
                <div>本关分数: ${totalScore}</div>
                <div>时间奖励: ${timeBonus}</div>
                <div>关卡: ${this.currentLevel}/20</div>
            `;
            menu.classList.remove('hidden');
        }
    }
    
    nextLevel() {
        try {
            if (this.currentLevel >= this.maxLevel) {
                this.showGameComplete();
                return false;
            }
            
            // 清理当前关卡
            if (window.gameEngine) {
                window.gameEngine.zombies = [];
                window.gameEngine.bullets = [];
                window.gameEngine.particles = [];
                window.gameEngine.powerUps = [];
                window.gameEngine.bossProjectiles = [];
                window.gameEngine.floatingTexts = [];
            }
            
            this.currentLevel++;
            
            // 重置玩家血量
            if (window.player) {
                window.player.health = window.player.maxHealth;
                window.player.updateHealthUI();
            }
            
            // 隐藏关卡完成菜单
            const levelCompleteMenu = document.getElementById('levelCompleteMenu');
            if (levelCompleteMenu) {
                levelCompleteMenu.classList.add('hidden');
            }
            
            return this.startLevel(this.currentLevel);
        } catch (error) {
            console.error('进入下一关失败:', error);
            alert('进入下一关失败，请重试。');
            return false;
        }
    }
    
    showGameComplete() {
        // 创建史诗级游戏完成界面
        const completeDiv = document.createElement('div');
        completeDiv.style.cssText = `
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: linear-gradient(135deg, rgba(75, 0, 130, 0.95), rgba(139, 0, 0, 0.95));
            color: #FFD700; display: flex; flex-direction: column; justify-content: center; 
            align-items: center; z-index: 30000; font-family: 'Courier New', monospace;
        `;
        
        completeDiv.innerHTML = `
            <div style="text-align: center; animation: epicVictory 3s ease-in-out infinite;">
                <div style="font-size: 48px; margin-bottom: 20px;">🎉 史诗级胜利！ 🎉</div>
                <div style="font-size: 32px; color: #FF4500; margin-bottom: 15px;">恭喜！你拯救了世界！</div>
                <div style="font-size: 24px; margin-bottom: 20px;">
                    已完成所有20关的史诗挑战！<br>
                    击败了病毒原始体，终结了末日危机！
                </div>
                <div style="font-size: 20px; color: #32CD32; margin-bottom: 30px;">
                    最终分数: ${window.gameManager ? window.gameManager.score : 0}
                </div>
                <div style="font-size: 16px; color: #87CEEB; margin-bottom: 30px;">
                    • 征服了20个关卡<br>
                    • 击败了2个强大BOSS<br>
                    • 拯救了整个世界<br>
                    • 成为了真正的英雄！
                </div>
                <button id="epicRestartBtn" style="
                    padding: 15px 30px; font-size: 18px; background: linear-gradient(45deg, #FF4500, #FFD700);
                    color: white; border: none; border-radius: 10px; cursor: pointer;
                    box-shadow: 0 5px 15px rgba(255, 215, 0, 0.4);
                ">再次挑战</button>
            </div>
        `;
        
        document.body.appendChild(completeDiv);
        
        // 添加动画样式
        if (!document.getElementById('epicVictoryStyles')) {
            const styles = document.createElement('style');
            styles.id = 'epicVictoryStyles';
            styles.textContent = `
                @keyframes epicVictory {
                    0%, 100% { transform: scale(1); }
                    50% { transform: scale(1.05); }
                }
            `;
            document.head.appendChild(styles);
        }
        
        // 重启按钮事件
        document.getElementById('epicRestartBtn').addEventListener('click', () => {
            document.body.removeChild(completeDiv);
            this.resetToMenu();
        });
        
        // 10秒后自动返回菜单
        setTimeout(() => {
            if (completeDiv.parentNode) {
                document.body.removeChild(completeDiv);
                this.resetToMenu();
            }
        }, 10000);
    }
    
    resetToMenu() {
        this.currentLevel = 1;
        this.isLevelActive = false;
        
        if (window.gameEngine) {
            window.gameEngine.gameState = 'menu';
            document.getElementById('startMenu').classList.remove('hidden');
            document.getElementById('levelCompleteMenu').classList.add('hidden');
        }
    }
    
    updateLevelUI() {
        const levelElement = document.getElementById('currentLevel');
        if (levelElement) {
            levelElement.textContent = this.currentLevel;
        }
    }
    
    getCurrentLevelData() {
        return this.levels[this.currentLevel - 1];
    }
    
    saveProgress() {
        const progress = {
            currentLevel: this.currentLevel,
            maxLevelReached: Math.max(this.currentLevel, this.getMaxLevelReached()),
            score: window.gameManager ? window.gameManager.score : 0,
            timestamp: Date.now()
        };
        
        localStorage.setItem('zombieGameProgress', JSON.stringify(progress));
    }
    
    loadProgress() {
        const saved = localStorage.getItem('zombieGameProgress');
        if (saved) {
            try {
                const progress = JSON.parse(saved);
                return progress;
            } catch (e) {
                console.error('无法加载游戏进度:', e);
            }
        }
        return null;
    }
    
    getMaxLevelReached() {
        const progress = this.loadProgress();
        return progress ? progress.maxLevelReached : 1;
    }
    
    canContinueGame() {
        const progress = this.loadProgress();
        return progress && progress.currentLevel > 1;
    }
}

// 游戏管理器
class GameManager {
    constructor() {
        this.score = 0;
        this.levelScore = 0;
        this.lives = 3;
        this.gameStartTime = 0;
        this.isPaused = false;
        this.levelManager = new LevelManager();
    }
    
    startNewGame() {
        window.debugLog && window.debugLog('GameManager.startNewGame 开始');
        
        try {
            this.score = 0;
            this.levelScore = 0;
            this.lives = 3;
            this.gameStartTime = Date.now();
            window.debugLog && window.debugLog('游戏数据重置完成');
            
            // 初始化玩家
            const canvas = document.getElementById('gameCanvas');
            if (!canvas) {
                throw new Error('找不到游戏画布 gameCanvas');
            }
            window.debugLog && window.debugLog('创建玩家...');
            window.player = new Player(canvas.width / 2, canvas.height / 2);
            // 确保玩家血量为满血
            window.player.health = window.player.maxHealth;
            window.player.updateHealthUI();
            window.debugLog && window.debugLog('玩家创建成功，血量已重置为满血');
            
            // 重置肉鸽系统临时效果
            if (window.roguelikeSystem) {
                window.roguelikeSystem.resetTemporaryEffects();
                window.debugLog && window.debugLog('肉鸽系统临时效果已重置');
            }
            
            // 应用永久升级效果到玩家
            if (window.roguelikeSystem && typeof window.roguelikeSystem.applyPermanentUpgrades === 'function') {
                window.roguelikeSystem.applyPermanentUpgrades();
                window.debugLog && window.debugLog('永久升级效果已应用');
            }
            
            // 应用技能树效果到玩家
            if (window.newSkillTreeSystem && typeof window.newSkillTreeSystem.applySkillEffects === 'function') {
                window.newSkillTreeSystem.applySkillEffects();
                window.debugLog && window.debugLog('技能树效果已应用');
            }
            
            // 开始第一关
            window.debugLog && window.debugLog('开始第一关...');
            this.levelManager.startLevel(1);
            window.debugLog && window.debugLog('第一关启动完成');
            
            // 更新UI
            window.debugLog && window.debugLog('更新UI...');
            this.updateScoreUI();
            
            if (window.gameEngine) {
                window.gameEngine.gameState = 'playing';
                window.debugLog && window.debugLog('游戏状态设置为playing');
            } else {
                throw new Error('gameEngine 不可用');
            }
            
            window.debugLog && window.debugLog('✓ GameManager.startNewGame 完成');
        } catch (error) {
            console.error('GameManager.startNewGame 失败:', error);
            window.debugLog && window.debugLog('✗ GameManager.startNewGame 失败: ' + error.message);
            throw error;
        }
    }
    
    continueGame() {
        const progress = this.levelManager.loadProgress();
        if (!progress) {
            this.startNewGame();
            return;
        }
        
        this.score = progress.score || 0;
        this.gameStartTime = Date.now();
        
        // 初始化玩家
        const canvas = document.getElementById('gameCanvas');
        window.player = new Player(canvas.width / 2, canvas.height / 2);
        // 确保玩家血量为满血
        window.player.health = window.player.maxHealth;
        window.player.updateHealthUI();
        
        // 应用永久升级效果到玩家
        if (window.roguelikeSystem && typeof window.roguelikeSystem.applyPermanentUpgrades === 'function') {
            window.roguelikeSystem.applyPermanentUpgrades();
            window.debugLog && window.debugLog('永久升级效果已应用（继续游戏）');
        }
        
        // 应用技能树效果到玩家
        if (window.newSkillTreeSystem && typeof window.newSkillTreeSystem.applySkillEffects === 'function') {
            window.newSkillTreeSystem.applySkillEffects();
            window.debugLog && window.debugLog('技能树效果已应用（继续游戏）');
        }
        
        // 继续关卡
        this.levelManager.startLevel(progress.currentLevel);
        
        // 更新UI
        this.updateScoreUI();
        
        if (window.gameEngine) {
            window.gameEngine.gameState = 'playing';
        }
    }
    
    addScore(points) {
        this.score += points;
        this.levelScore += points;
        this.updateScoreUI();
    }
    
    subtractScore(points) {
        this.score = Math.max(0, this.score - points);
        this.levelScore = Math.max(0, this.levelScore - points);
        this.updateScoreUI();
    }
    
    getLevelScore() {
        return this.levelScore;
    }
    
    nextLevel() {
        this.levelScore = 0;
        return this.levelManager.nextLevel();
    }
    
    updateScoreUI() {
        const scoreElement = document.getElementById('scoreValue');
        if (scoreElement) {
            scoreElement.textContent = this.score;
        }
    }
    
    gameOver() {
        if (window.gameEngine) {
            window.gameEngine.gameState = 'gameOver';
        }
        
        // 保存最高分
        const highScore = localStorage.getItem('zombieGameHighScore');
        if (!highScore || this.score > parseInt(highScore)) {
            localStorage.setItem('zombieGameHighScore', this.score.toString());
        }
    }
    
    pauseGame() {
        this.isPaused = true;
        if (window.gameEngine) {
            window.gameEngine.gameState = 'paused';
        }
    }
    
    resumeGame() {
        this.isPaused = false;
        if (window.gameEngine) {
            window.gameEngine.gameState = 'playing';
        }
    }
}